package com.lcsc.verification.core;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    private static final Map<String,JdbcTemplate> jdbcTemplateMap = Maps.newHashMap();

    public JdbcTemplate getJdbcTemplate(String key) {

        JdbcTemplate jdbcTemplate = jdbcTemplateMap.get(key + "_template");

        if (jdbcTemplate == null) {

            switch (key) {

                case "order":
                    jdbcTemplate = getTemplate(getOrderDataSource());
                    break;
                case "pay":
                    jdbcTemplate = getTemplate(getPayDataSource());
                    break;
                case "sps":
                    jdbcTemplate = getTemplate(getSpsDataSource());
                    break;
                default:
                    break;
            }

            if (jdbcTemplate != null) {

                jdbcTemplateMap.put(key + "_template",jdbcTemplate);
            }
        }

        return jdbcTemplate;
    }

    @Bean(name = "vcDataSource")
    @Primary
    @Qualifier("vcDataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource getSystemDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "orderDataSource")
    @Qualifier("orderDataSource")
    @ConfigurationProperties(prefix="config.order")
    public DataSource getOrderDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "payDataSource")
    @Qualifier("payDataSource")
    @ConfigurationProperties(prefix="config.pay")
    public DataSource getPayDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "spsDataSource")
    @Qualifier("spsDataSource")
    @ConfigurationProperties(prefix="config.sps")
    public DataSource getSpsDataSource() {
        return DataSourceBuilder.create().build();
    }

    public JdbcTemplate getTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}
